package his.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import his.entity.*;
import his.persistence.*;
import his.vo.DepartmentVO;
import his.vo.MedicalRecordVO;
import his.vo.PayVO;
import his.vo.RegisterVO;
import his.service.RegisterService;
import org.apache.ibatis.annotations.Update;
import org.example.his.common.api.CommonResponse;
import org.example.his.common.auth.JwtAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class RegisterServiceImpl implements RegisterService {
    //mapper注入
    @Autowired
    RegisterMapper registerMapper;
    @Autowired
    RegisterLevelMapper registerLevelMapper;
    @Autowired
    PatientMapper patientMapper;
    @Autowired
    CheckApplyMapper checkApplyMapper;
    @Autowired
    PatientCostsMapper patientCostsMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    VoucherMapper voucherMapper;
    @Autowired
    DrugsMapper drugsMapper;
    @Autowired
    FmedItemMapper fmedItemMapper;
    @Autowired
    PrescriptionMapper prescriptionMapper;
    @Autowired
    PrescriptionDetailedMapper prescriptionDetailedMapper;
    @Autowired
    MedicalRecordMapper medicalRecordMapper;
    @Autowired
    ConstantItemMapper constantItemMapper;
    @Autowired
    DepartmentMapper departmentMapper;


    @Override
    public CommonResponse pay_func(String casenumber) {
        QueryWrapper<MedicalRecord> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("CaseNumber",casenumber);
        queryWrapper1.ne("CaseState",3);
        MedicalRecord medicalRecord=medicalRecordMapper.selectOne(queryWrapper1);
        int registid=medicalRecord.getRegistID();

        CommonResponse<List<MedicalRecordVO>> tempcom=this.search_patient_cost(casenumber);
        List<MedicalRecordVO> medicalRecordVOList=tempcom.getData();
        System.out.println(medicalRecordVOList.size());
        for(int i=0;i<medicalRecordVOList.size();i++){
            MedicalRecordVO m=medicalRecordVOList.get(i);
            if(m.getState().equals("已开立")){
                Voucher voucher=new Voucher();
                voucher.setCreationTime(new Date());
                voucher.setRegistID(registid);
                voucher.setMoney(m.getPrice().multiply(m.getAmount()));
                List<String> voucherNum = voucherMapper.getVoucherNum();
                //设置为最小值 方便之后更新
                int maxVoucherNum = Integer.MIN_VALUE;
                for (String age : voucherNum) {
                    int VoucherNumInt = Integer.parseInt(age);
                    if (VoucherNumInt > maxVoucherNum) {
                        maxVoucherNum = VoucherNumInt;
                    }
                }
                voucher.setVoucherNum(Integer.toString(maxVoucherNum+1));
                voucherMapper.insert(voucher);
            }

        }

        UpdateWrapper<CheckApply> updateWrapper1=new UpdateWrapper<>();
        updateWrapper1.eq("MedicalID",medicalRecord.getID());
        updateWrapper1.eq("State",2);
        updateWrapper1.set("State",3);
        checkApplyMapper.update(null,updateWrapper1);
//        QueryWrapper<CheckApply> queryWrapper2=new QueryWrapper<>();
//        queryWrapper2.eq("MedicalID",medicalRecord.getID());
//        queryWrapper2.eq("State",2);
//        CheckApply checkApply=new CheckApply();
//        checkApply.setState(3);
//        int result=checkApplyMapper.update(checkApply,queryWrapper2);
        QueryWrapper<Prescription> queryWrapper3=new QueryWrapper<>();
        queryWrapper3.eq("MedicalID",medicalRecord.getID());
        queryWrapper3.eq("PrescriptionState",2);
        List<Prescription> prescriptionList=prescriptionMapper.selectList(queryWrapper3);
        for(int j=0;j<prescriptionList.size();j++){
            QueryWrapper<PrescriptionDetailed> queryWrapper4=new QueryWrapper<>();
            queryWrapper4.eq("PrescriptionID",prescriptionList.get(j).getID());
            queryWrapper4.eq("State",2);
            List<PrescriptionDetailed> prescriptionDetailedList=prescriptionDetailedMapper.selectList(queryWrapper4);
            if(prescriptionDetailedList.size()>0){
                for(int k=0;k<prescriptionDetailedList.size();k++){
                    PrescriptionDetailed temp=prescriptionDetailedList.get(k);
                    UpdateWrapper<PrescriptionDetailed> updateWrapper2=new UpdateWrapper<>();
                    updateWrapper2.eq("PrescriptionID",prescriptionList.get(j).getID());
                    updateWrapper2.eq("State",2);
                    updateWrapper2.eq("DrugsID",temp.getDrugsID());
                    updateWrapper2.set("State",3);
                    updateWrapper2.set("PrescriptionID",temp.getPrescriptionID());
                    updateWrapper2.set("DrugsID",temp.getDrugsID());
                    prescriptionDetailedMapper.update(null,updateWrapper2);

//                    PrescriptionDetailed p=new PrescriptionDetailed();
//                    p.setDrugsID(temp.getDrugsID());
//                    p.setPrescriptionID(temp.getPrescriptionID());
//                    p.setState(3);
//                    QueryWrapper<PrescriptionDetailed> queryWrapper5=new QueryWrapper<>();
//                    queryWrapper5.eq("PrescriptionID",prescriptionList.get(j).getID());
//                    queryWrapper5.eq("State",2);
//                    queryWrapper5.eq("DrugsID",temp.getDrugsID());
//                    prescriptionDetailedMapper.update(p,queryWrapper5);
                }
            }
//            PrescriptionDetailed prescriptionDetailed=new PrescriptionDetailed();
//            prescriptionDetailed.setState(3);
//            int result1=prescriptionDetailedMapper.update(prescriptionDetailed,queryWrapper4);
        }

        return CommonResponse.createForSuccess("缴费成功");
    }


    @Override
    public CommonResponse<List<Voucher>> getvoucher(String casenumber) {
        List<Voucher> vouchers=new ArrayList<>();

        QueryWrapper<Register> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("CaseNumber",casenumber);
        List<Register> registerList=registerMapper.selectList(queryWrapper1);
        for(int i=0;i<registerList.size();i++){
            Register register=registerList.get(i);
            QueryWrapper<Voucher> queryWrapper2=new QueryWrapper<>();
            queryWrapper2.eq("RegistID",register.getId());
            List<Voucher> voucherList=voucherMapper.selectList(queryWrapper2);

            vouchers.addAll(voucherList);
        }
        return CommonResponse.createForSuccess(vouchers);
    }


    @Override
    public CommonResponse<String> get_casenumber(String token) {

        if(!JwtAuth.checkToken(token)){
            return CommonResponse.createForSuccess("token无效");
        }else{
            String openid=JwtAuth.jwtDecrypt(token);
            QueryWrapper<Patient> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("OpenID",openid);
            Patient patient=patientMapper.selectOne(queryWrapper);
            if(patient==null){
                return CommonResponse.createForError("未找到该就诊人");
            }else{
                return CommonResponse.createForSuccess(patient.getCaseNumber());
            }
        }

    }

    @Override
    public CommonResponse check_token(String token) {
        if(JwtAuth.checkToken(token)){
            return CommonResponse.createForSuccess("token有效");
        }else{
            return CommonResponse.createForError("token无效");
        }

    }

    //接口实现
      public CommonResponse<List<Register>> get_searchregister(String CaseNumber){
        QueryWrapper<Register> registerQueryWrapper = new QueryWrapper<>();
        registerQueryWrapper.eq("CaseNumber" , CaseNumber);
        List<Register> registerList = registerMapper.selectList(registerQueryWrapper);
        if(!registerList.isEmpty()){
            return CommonResponse.createForSuccess(registerList);
        }else return CommonResponse.createForError("未找到挂号信息");
    }

      //增加挂号信息
      public CommonResponse<RegisterVO> add_new_register(String RealName, String Gender, int Age, String BirthDate, String IDnumber, String HomeAddress, int RegistLeID, int DeptID, int UserID, char isBook, int RegisterID, String Noon){
        QueryWrapper<Register> registerQueryWrapper = new QueryWrapper<>();
        QueryWrapper<RegisterLevel> registerLevelQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Patient> patientQueryWrapper = new QueryWrapper<>();
        Patient patient = new Patient();
        Register register = new Register();
        RegisterLevel registerLevel = new RegisterLevel();
        RegisterVO registerVO = new RegisterVO();
        registerQueryWrapper.eq("RealName" , RealName);
        List<Register> registerList = registerMapper.selectList(registerQueryWrapper);
             /* 逻辑：
               当用户之前挂过号时，在挂号记录中查找CaseNumber，只更改记录的USerID，RegisterID，时间等信息
               病历号不变
               （系统中用户永远只有一个病历号）
             */
        if(!registerList.isEmpty()){
            Register register2 = new Register();
            register2.setRealName(RealName);
            if(Gender.equals("男")){
                register2.setGender(71);
            }else register2.setGender(72);
            register2.setCaseNumber(registerList.get(0).getCaseNumber());
            register2.setRegistTime(new Date());
            register2.setVisitDate(new Date());
            Date current_time = new Date();
            int current_time_hour = current_time.getHours();
            if(current_time_hour >= 0 && current_time_hour <= 12){
                register2.setNoon("上午");
            }else register2.setNoon("下午");
            register2.setDeptID(DeptID);
            register2.setUserID(UserID);
            register2.setRegistLeID(RegistLeID);
            register2.setIsBook(isBook);
            register2.setRegisterID(RegisterID);
            register2.setVisitState(2);
            patientQueryWrapper.eq("CaseNumber" , registerList.get(0).getCaseNumber());
            register2.setPatientId(patientMapper.selectOne(patientQueryWrapper).getId());
            //将新纪录插入到数据库中
            registerMapper.insert(register2);
            registerLevelQueryWrapper.eq("ID" , RegistLeID);
            RegisterLevel registerLevel1 = registerLevelMapper.selectOne(registerLevelQueryWrapper);
            RegisterVO registerVO1 = entityToRegisterVO(register2, registerLevel1);
            return CommonResponse.createForSuccess(registerVO1);
        }
        else if(registerList.isEmpty()){
            /* 逻辑：
                若用户之前没有挂过号，即patient表中并没有用户的信息，register中也没有，而用户选择了现场挂号
                此时，生成新的病历号，将用户的基本信息添加到patient和Register表中
             */
            //获取病历号最大值，加一生成最新的病历号
            List<String> CaseNumberList = registerMapper.getCaseNumberList();
            //设置为最小值 方便之后更新
            int maxCaseNumber = Integer.MIN_VALUE;
            for (String age : CaseNumberList) {
                int CaseNumberInt = Integer.parseInt(age);
                if (CaseNumberInt > maxCaseNumber) {
                    maxCaseNumber = CaseNumberInt;
                }
            }
            Register register3 = new Register();
            Patient patient1 = new Patient();
            register3.setCaseNumber(Integer.toString(maxCaseNumber+1));

            //patient数据增加
            patient1.setCaseNumber(register3.getCaseNumber());
            patient1.setRealName(RealName);
            if(Gender.equals("男")){
                patient1.setGender(71);
            }else patient1.setGender(72);
            patient1.setIDnumber(IDnumber);

            String pattern = "yyyy-MM-dd";
           //时分秒转换HH:mm:ss

            Date BirthDate_Date = parseDateTimeString(BirthDate , pattern);
            patient1.setBirthDate(BirthDate_Date);
            patient1.setAge(Age);
            patient1.setAgeType('1');
            patient1.setHomeAddress(HomeAddress);
            patientMapper.insert(patient1);

            patientQueryWrapper.eq("CaseNumber" , register3.getCaseNumber());
            register3.setPatientId(patientMapper.selectOne(patientQueryWrapper).getId());
            register3.setRealName(RealName);
            if(Gender.equals("男")){
                register3.setGender(71);
            }else register3.setGender(72);
            register3.setRegistTime(new Date());
            register3.setVisitDate(new Date());

            //Noon
            Date current_time = new Date();
            int current_time_hour = current_time.getHours();
            if(current_time_hour >= 0 && current_time_hour <= 12){
                register3.setNoon("上午");
            }else register3.setNoon("下午");

            register3.setDeptID(DeptID);
            register3.setUserID(UserID);
            register3.setRegistLeID(RegistLeID);
            register3.setIsBook(isBook);
            register3.setRegisterID(RegisterID);
            register3.setVisitState(1);
            //将新纪录插入到数据库中
            registerMapper.insert(register3);
            registerLevelQueryWrapper.eq("ID" , RegistLeID);
            RegisterLevel registerLevel1 = registerLevelMapper.selectOne(registerLevelQueryWrapper);
            RegisterVO registerVO1 = entityToRegisterVO(register3, registerLevel1);
            return CommonResponse.createForSuccess(registerVO1);
        }else {
            return CommonResponse.createForError("挂号失败");
        }
   }

      //退号
      public CommonResponse<Register> dele_regist(String CaseNumber , int VisitState){
      QueryWrapper<Register> registerQueryWrapper = new QueryWrapper<>();
      registerQueryWrapper.eq("CaseNumber" , CaseNumber).eq("VisitState" , VisitState);
        Register register = registerMapper.selectOne(registerQueryWrapper);
        if(register!=null){
            registerMapper.delete(registerQueryWrapper);
            return CommonResponse.createForSuccess(register);
        }
       else return CommonResponse.createForError("退号失败");
    }
      //搜索用户所有项目
    //根据medicalID查出
      public  CommonResponse<List<MedicalRecordVO>> search_patient_cost(String CaseNumber){
        //Bean注入
        CheckApply checkApply = new CheckApply();
        Patient patient = new Patient();
        PatientCosts patientCosts = new PatientCosts();
        Register register = new Register();
        MedicalRecord medicalRecord = new MedicalRecord();
        Prescription prescription = new Prescription();
        PrescriptionDetailed prescriptionDetailed = new PrescriptionDetailed();
        List<CheckApply> checkApplyList = new ArrayList<>();
        List<MedicalRecordVO> patientCostVOList = new ArrayList<>();
        //QueryWrapper
        QueryWrapper<Register> registerQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Patient> patientQueryWrapper = new QueryWrapper<>();
        QueryWrapper<CheckApply> checkApplyQueryWrapper = new QueryWrapper<>();
        QueryWrapper<MedicalRecord> medicalRecordQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Prescription> prescriptionQueryWrapper  = new QueryWrapper<>();
        //逻辑
        registerQueryWrapper.eq("CaseNumber" , CaseNumber);
        List<Register> registerList = registerMapper.selectList(registerQueryWrapper);
          String RealName = registerList.get(0).getRealName();
          patientQueryWrapper.eq("RealName" , RealName);
          patient = patientMapper.selectOne(patientQueryWrapper);

            //找到两个list
            medicalRecordQueryWrapper.eq("CaseNumber" , CaseNumber);
            /**/
            List<MedicalRecord> medicalRecords = medicalRecordMapper.selectList(medicalRecordQueryWrapper);
            //最外层循环
            for(int j =0 ; j < medicalRecords.size();j ++){
                MedicalRecord medicalRecord1 = medicalRecords.get(j);
                /*按照找项目类别找出两个list*/
                checkApplyQueryWrapper.eq("MedicalID" , medicalRecord1.getID());
                List<CheckApply> checkApplyList1 = checkApplyMapper.selectList(checkApplyQueryWrapper);
                prescriptionQueryWrapper.eq("MedicalID" , medicalRecord1.getID());
                List<Prescription> prescriptions = prescriptionMapper.selectList(prescriptionQueryWrapper);

                //遍历项目执行列表
                for(int l = 0;l<checkApplyList1.size();l++){
                    CheckApply checkApply1 = checkApplyList1.get(l);
                    int itemID = checkApply1.getItemID();
                    int registID = checkApply1.getRegistID();
                    QueryWrapper<FmedItem> fmedItemQueryWrapper = new QueryWrapper<>();
                    fmedItemQueryWrapper.eq("ID" , itemID);
                    BigDecimal price = fmedItemMapper.selectOne(fmedItemQueryWrapper).getPrice();
                    MedicalRecordVO medicalRecordVO = entityToPatientCostVO(patient, checkApply1);
                    //新增的返回的三条数据
                    medicalRecordVO.setItemID(itemID);
                    medicalRecordVO.setItemType(1);
                    medicalRecordVO.setRegistID(registID);
                    medicalRecordVO.setPrice(price);
                    patientCostVOList.add(medicalRecordVO);
                }
                //便利处方列表
                for(int k=0;k<prescriptions.size();k++){
                    Prescription prescription1 = prescriptions.get(k);
                    int registID = prescription1.getRegistID();
                    QueryWrapper<PrescriptionDetailed> prescriptionDetailedQueryWrapper = new QueryWrapper<>();
                    prescriptionDetailedQueryWrapper.eq( "PrescriptionID" ,prescription1.getID());
                    //获取每个prescription对应的id 对应的多个明细
                    List<PrescriptionDetailed> prescriptionDetaileds = prescriptionDetailedMapper.selectList(prescriptionDetailedQueryWrapper);
                    for(int m = 0;m<prescriptionDetaileds.size();m++){
                        PrescriptionDetailed prescriptionDetailed1 = prescriptionDetaileds.get(m);
                        int drugsID = prescriptionDetailed1.getDrugsID();
                        QueryWrapper<Drugs> drugsQueryWrapper =  new QueryWrapper<>();
                        drugsQueryWrapper.eq("ID" ,drugsID);
                        String drugsName = drugsMapper.selectOne(drugsQueryWrapper).getDrugsName();
                        BigDecimal drugsPrice = drugsMapper.selectOne(drugsQueryWrapper).getDrugsPrice();
                        MedicalRecordVO medicalRecordVO = entityToMedicalVO(patient, prescriptionDetailed1);
                        medicalRecordVO.setItemType(2);
                        medicalRecordVO.setItemID(drugsID);
                        medicalRecordVO.setName(drugsName);
                        medicalRecordVO.setRegistID(registID);
                        medicalRecordVO.setPrice(drugsPrice);
                        patientCostVOList.add(medicalRecordVO);
                    }
                }
            }
            if(!patientCostVOList.isEmpty()){
            return CommonResponse.createForSuccess(patientCostVOList);
           }
        return CommonResponse.createForError("查找失败");
    }



    //收费
    /*逻辑
    更改状态为已收费，生成新的voucher加入到voucher表中
    */
    @Override
    public CommonResponse<PayVO> pay(String CaseNumber, int ItemID, int RegistID, BigDecimal totalPrice , int ItemType) {
        //根据CaseNumber RegistID找到对应的userID
        QueryWrapper<Register> registerQueryWrapper = new QueryWrapper<>();
        registerQueryWrapper.eq("CaseNumber" , CaseNumber).eq("ID" , RegistID);
        Register register = registerMapper.selectOne(registerQueryWrapper);
        //获取到挂号员的id
        int userID = register.getRegisterID();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("ID" , userID);
        User register_people = userMapper.selectOne(userQueryWrapper);
        PayVO payVO = entityToPayVO(CaseNumber , register , register_people);
        //生成对应的凭证 voucher 一个项目一个
        /*
        对应逻辑，生成voucher号,添加对应的信息
         */
        Voucher voucher = new Voucher();
        voucher.setUserID(register_people.getId());
        voucher.setRegistID(register.getId());
        voucher.setMoney(totalPrice);
        voucher.setCreationTime(new Date());
        voucher.setItemID(ItemID);

        //可封装
        List<String> voucherNum = voucherMapper.getVoucherNum();
        //设置为最小值 方便之后更新
        int maxVoucherNum = Integer.MIN_VALUE;
        for (String age : voucherNum) {
            int VoucherNumInt = Integer.parseInt(age);
            if (VoucherNumInt > maxVoucherNum) {
                maxVoucherNum = VoucherNumInt;
            }
        }
        voucher.setVoucherNum(Integer.toString(maxVoucherNum+1));
        //生成新的voucher添加到表中
        voucherMapper.insert(voucher);

          /*
           先生成voucher后，将数据插入patient cost
        * */
        PatientCosts patientCosts = new PatientCosts();
        patientCosts.setRegistID(RegistID);
        patientCosts.setItemID(ItemID);
        patientCosts.setVoucherID(voucher.getID());
        patientCosts.setCreateTime(new Date());
        patientCosts.setPrice(totalPrice);
        patientCosts.setDeptID(register.getDeptID());
        patientCosts.setPayTime(new Date());
        patientCosts.setRegisterID(userID);
        patientCosts.setBackID(0);
        patientCosts.setItemType(ItemType);
        if (ItemType==1){
            QueryWrapper<FmedItem> fmedItemQueryWrapper = new QueryWrapper<>();
            fmedItemQueryWrapper.eq("ID" , ItemID) ;
            FmedItem fmedItem = fmedItemMapper.selectOne(fmedItemQueryWrapper);
            patientCosts.setName(fmedItem.getItemName());
            patientCosts.setAmount(totalPrice.divide(fmedItem.getPrice()));
        }else if(ItemType == 2){
            QueryWrapper<Drugs> drugsQueryWrapper = new QueryWrapper<>();
            drugsQueryWrapper.eq("ID" , ItemID);
            Drugs drugs = drugsMapper.selectOne(drugsQueryWrapper);
            patientCosts.setName(drugs.getDrugsName());
            patientCosts.setAmount(totalPrice.divide(drugs.getDrugsPrice()));
        }
        patientCostsMapper.insert(patientCosts);
        //将状态改为已收费  checkapply
        if(payVO != null){
            return CommonResponse.createForSuccess(payVO);
        }
        return CommonResponse.createForError("收费失败");
    }

    //退费
    public CommonResponse<String> refunds(int RegistID , String CaseNumber,int ItemID, BigDecimal price, int ItemType, String Status ,BigDecimal totalPrice) {
        if(Status.equals("已交费")){
            System.out.println("TestPoint");
            //根据CaseNumber RegistID找到对应的userID
            QueryWrapper<Register> registerQueryWrapper = new QueryWrapper<>();
            registerQueryWrapper.eq("CaseNumber" , CaseNumber).eq("ID" , RegistID);
            Register register = registerMapper.selectOne(registerQueryWrapper);
            int registerID = register.getRegisterID();
            //获取到挂号员的id
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("ID" , registerID);
            User register_people = userMapper.selectOne(userQueryWrapper);
            //生成对应的凭证 voucher 一个项目一个
        /*
        对应逻辑，生成voucher号,添加对应的信息
         */
            Voucher voucher = new Voucher();
            voucher.setUserID(register_people.getId());
            voucher.setMoney(totalPrice);
            voucher.setCreationTime(new Date());
            voucher.setItemID(ItemID);
            List<String> voucherNum = voucherMapper.getVoucherNum();
            //设置为最小值 方便之后更新
            int maxVoucherNum = Integer.MIN_VALUE;
            for (String age : voucherNum) {
                int VoucherNumInt = Integer.parseInt(age);
                if (VoucherNumInt > maxVoucherNum) {
                    maxVoucherNum = VoucherNumInt;
                }
            }
            System.out.println(maxVoucherNum);
            voucher.setVoucherNum(Integer.toString(maxVoucherNum+1));
            //生成新的voucher添加到表中
            voucherMapper.insert(voucher);
            System.out.println("Test");
            //更改checkapply中的状态
            //test
            UpdateWrapper<CheckApply> checkApplyUpdateWrapper =new UpdateWrapper<>();
            checkApplyUpdateWrapper.set("State" , 0);
            checkApplyUpdateWrapper.eq("ItemID" ,ItemID ).eq("RegistID" , RegistID);
            checkApplyMapper.update(null , checkApplyUpdateWrapper);

            //若项目为药品 更改处方表中的各药品的状态
            if(ItemType == 2){
                 QueryWrapper<Prescription> prescriptionQueryWrapper = new QueryWrapper<>();
                 prescriptionQueryWrapper.eq("RegistID" , RegistID);
                List<Prescription> prescriptions = prescriptionMapper.selectList(prescriptionQueryWrapper);
                QueryWrapper<PrescriptionDetailed> prescriptionDetailedQueryWrapper = new QueryWrapper<>();
                for(int i=0 ; i < prescriptions.size() ; i++){
                    int id = prescriptions.get(i).getID();
                    UpdateWrapper<Prescription> prescriptionUpdateWrapper =new UpdateWrapper<>();
                    prescriptionUpdateWrapper.set("PrescriptionState" ,0 );
                    prescriptionUpdateWrapper.eq("ID" ,id );
                    prescriptionMapper.update(null , prescriptionUpdateWrapper);
                }
            }
            return CommonResponse.createForSuccess("退费成功");
        }
        else return CommonResponse.createForError("当前状态无法退费");
    }

     //转换Date数据格式
      public static Date parseDateTimeString(String dateTimeString, String pattern) {
        SimpleDateFormat dateTimeFormat = new SimpleDateFormat(pattern);
        try {
            Date parsedDateTime = dateTimeFormat.parse(dateTimeString);
            return parsedDateTime;
        }catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }
     //转化RegisterVO
      public static RegisterVO entityToRegisterVO(Register register , RegisterLevel registerLevel){
        RegisterVO registerVO = new RegisterVO();
//        if(patient!=null){
////            registerVO.setAge(patient.getAge());
////            registerVO.setGender(patient.getGender());
////            registerVO.setBirthDate(patient.getBirthDate());
////            registerVO.setIDnumber(patient.getIDnumber());
//        }
        if(register!=null){
            registerVO.setCaseNumber(register.getCaseNumber());
//            registerVO.setRealName(register.getRealName());
//            registerVO.setRegistLeID(register.getRegistLeID());
//            registerVO.setDeptID(register.getDeptID());
////            registerVO.setRegistTime(register.getRegistTime());
//            registerVO.setUserID(register.getUserID());
//            registerVO.setNoon(register.getNoon());
//            registerVO.setIsBook(register.getIsBook());
        }
        if(registerLevel!=null){
            registerVO.setPrice(registerLevel.getRegistFee());
        }
        return registerVO;
      }

    @Override
    public CommonResponse<List<User>> get_doctors(int depar_id) {
        QueryWrapper<User> userQueryWrapper =new QueryWrapper<>();
        userQueryWrapper.eq("DeptID" , depar_id);
        List<User> users = userMapper.selectList(userQueryWrapper);
        if(!users.isEmpty()){
            return CommonResponse.createForSuccess(users);
        }
        return CommonResponse.createForError("数据为空，暂无医生");
    }

    //获取部门列表
    @Override
    public CommonResponse<List<DepartmentVO>> get_depar_lists() {
        QueryWrapper<ConstantItem> constantItemQueryWrapper = new QueryWrapper<>();
        constantItemQueryWrapper.eq("ConstantTypeID" ,1);
        List<ConstantItem> constantItems = constantItemMapper.selectList(constantItemQueryWrapper);
        List<DepartmentVO> departmentVOS = new ArrayList<>();
        for(ConstantItem constantItem: constantItems){
              QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
              departmentQueryWrapper.eq("DeptCategoryID" , constantItem.getID());
            List<Department> departments = departmentMapper.selectList(departmentQueryWrapper);
            DepartmentVO departmentVO = entityTODepartmentVO(constantItem, departments);
            departmentVOS.add(departmentVO);
        }
        return CommonResponse.createForSuccess(departmentVOS);
    }
    //实体转话为PatientCostVO
    public static MedicalRecordVO entityToPatientCostVO(Patient patient , CheckApply checkApply){
        MedicalRecordVO patientCostVO = new MedicalRecordVO();
        if(patient!=null){
            patientCostVO.setCaseNumber(patient.getCaseNumber());
            patientCostVO.setRealName(patient.getRealName());
            patientCostVO.setIDnumber(patient.getIDnumber());
            patientCostVO.setHomeAddress(patient.getHomeAddress());
        }
        if(checkApply!=null) {
            int num = checkApply.getState();
            switch (num){
                case 0:
                    patientCostVO.setState("已作废");
                    break;
                case 1:
                    patientCostVO.setState("暂存");
                    break;
                case 2:
                    patientCostVO.setState("已开立");
                    break;
                case 3:
                    patientCostVO.setState("已交费");
                    break;
                case 4:
                    patientCostVO.setState("已登记");
                    break;
                case 5:
                    patientCostVO.setState("执行完");
                    break;
                case 6:
                    patientCostVO.setState("已退费");
                    break;
            }
            patientCostVO.setName(checkApply.getName());
            patientCostVO.setAmount(checkApply.getNum());
        }
        patientCostVO.setCreateTime(new Date());
        return patientCostVO;
    }
    @Override
    public CommonResponse<String> regist_xcx(int doc_id, String token) {
        QueryWrapper<Patient> patientQueryWrapper = new QueryWrapper<>();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if(JwtAuth.checkToken(token)){
            String openid = JwtAuth.jwtDecrypt(token);
            patientQueryWrapper.eq("OpenID" , openid);
            //根据openid查找到patient
            Patient patient = patientMapper.selectOne(patientQueryWrapper);
            //获取病历号
            String caseNumber = patient.getCaseNumber();
            int patientId = patient.getId();
            String realName = patient.getRealName();
            int gender = patient.getGender();

            //插入表中的对象
            Register register = new Register();
            register.setCaseNumber(caseNumber);
            userQueryWrapper.eq("ID" , doc_id);
            User registed_doctor = userMapper.selectOne(userQueryWrapper);
            register.setRegistLeID(registed_doctor.getRegistLeID());
            register.setUserID(registed_doctor.getId());
            registed_doctor.setDeptID(registed_doctor.getDeptID());
            register.setPatientId(patientId);
            //设置状态为医生接诊
            register.setVisitState(2);
            register.setRegistTime(new Date());
            register.setGender(gender);
            register.setRealName(realName);
            Date current_time = new Date();
            int current_time_hour = current_time.getHours();
            if(current_time_hour >= 0 && current_time_hour <= 12){
                register.setNoon("上午");
            }else register.setNoon("下午");
            registerMapper.insert(register);
            /*收费逻辑:
            生成一条voucher和一条PatientCosts
            顺序为：先生成一条voucher
            */
            Voucher voucher = new Voucher();
            List<String> voucherNum = voucherMapper.getVoucherNum();
            //设置为最小值 方便之后更新
            int maxVoucherNum = Integer.MIN_VALUE;
            for (String age : voucherNum) {
                int VoucherNumInt = Integer.parseInt(age);
                if (VoucherNumInt > maxVoucherNum) {
                    maxVoucherNum = VoucherNumInt;
                }
            }
            voucher.setVoucherNum(Integer.toString(maxVoucherNum+1));
            if(registed_doctor.getRegistLeID()==1){
                //专家号
                voucher.setMoney(BigDecimal.valueOf(50.00));
            }else{
                //普通号
                voucher.setMoney(BigDecimal.valueOf(10.00));
            }
                voucher.setCreationTime(new Date());
            //8888表示使用手机小程序挂号
                voucher.setUserID(8888);
                voucher.setRegistID(register.getId());
                voucher.setItemID(57);
                voucherMapper.insert(voucher);

                /*添加记录到patientCosts
                **/
            PatientCosts patientCosts = new PatientCosts();
            patientCosts.setRegistID(register.getId());
            patientCosts.setVoucherID(voucher.getID());
            patientCosts.setItemID(voucher.getItemID());
            patientCosts.setItemType(1);
            patientCosts.setName("小程序挂号");
            patientCosts.setPrice(voucher.getMoney());
            patientCosts.setAmount(BigDecimal.valueOf(1));
            patientCosts.setPayTime(new Date());
            patientCosts.setRegisterID(8888);
            patientCosts.setCreateTime(new Date());

            patientCostsMapper.insert(patientCosts);
            return CommonResponse.createForSuccess("挂号成功");
        }else return CommonResponse.createForSuccess("Token无效");
    }

    public static MedicalRecordVO entityToMedicalVO(Patient patient , PrescriptionDetailed prescriptionDetailed){
        MedicalRecordVO patientCostVO = new MedicalRecordVO();
        if(patient!=null){
            patientCostVO.setCaseNumber(patient.getCaseNumber());
            patientCostVO.setRealName(patient.getRealName());
            patientCostVO.setIDnumber(patient.getIDnumber());
            patientCostVO.setHomeAddress(patient.getHomeAddress());
        }
        if(prescriptionDetailed!=null) {
            int num = prescriptionDetailed.getState();
            switch (num){
                case 0:
                    patientCostVO.setState("已作废");
                    break;
                case 1:
                    patientCostVO.setState("暂存");
                    break;
                case 2:
                    patientCostVO.setState("已开立");
                    break;
                case 3:
                    patientCostVO.setState("已交费");
                    break;
                case 4:
                    patientCostVO.setState("已发药");
                    break;
                case 5:
                    patientCostVO.setState("已退药");
                    break;
                case 6:
                    patientCostVO.setState("已退费");
                    break;
            }
        }
        patientCostVO.setAmount(prescriptionDetailed.getAmount());
        patientCostVO.setCreateTime(new Date());
        return patientCostVO;
    }

    public static PayVO entityToPayVO(String CaseNumber , Register register , User user){
       PayVO payVO = new PayVO();
       if(!CaseNumber.equals(" ")){
           payVO.setCaseNumber(CaseNumber);
       }
       if(register != null){
           payVO.setRegistID(register.getId());
       }
       if(user != null){
           payVO.setUsername(user.getUserName());
       }
       payVO.setCreateTime(new Date());
       return payVO;
      }

      public static DepartmentVO entityTODepartmentVO(ConstantItem constantItem , List<Department> departments){
      DepartmentVO departmentVO = new DepartmentVO();
      departmentVO.setDepart_Cate(constantItem.getConstantName());
      departmentVO.setItemList(departments);
      return departmentVO;
      }

      public  static  Register set_Noon(Register register){
          Date current_time = new Date();
          int current_time_hour = current_time.getHours();
          if(current_time_hour >= 0 && current_time_hour <= 12){
              register.setNoon("上午");
          }else register.setNoon("下午");
          return register;
      }
}

